package com.ruoyi.base.aop;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.base.annotaion.PermissionCheck;
import com.ruoyi.base.utils.servlet.ServletUtils;
import com.ruoyi.base.utils.spring.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Before;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * 解析PathVariable注释的参数
 *
 * @author lcf
 */
//@Aspect
//@Component
public class ParamAspect {

    @Before("execution(* com.ruoyi.platform.*.controller.*.*(..))")
    public void aroundAdvice() throws Exception {
        HttpServletRequest request = ServletUtils.getRequest();
        RequestMappingHandlerMapping handlerMapping = SpringUtils.getBean(RequestMappingHandlerMapping.class);
        HandlerExecutionChain handlerExecutionChain = handlerMapping.getHandler(request);
        HandlerMethod handlerMethod = (HandlerMethod) handlerExecutionChain.getHandler();
        Method method = handlerMethod.getMethod();

        PermissionCheck authorityCheck = method.getAnnotation(PermissionCheck.class);
        if (authorityCheck == null) {
            return;
        }

        //从parameter获取项目id
        String projectIdParam = request.getParameter("projectId");
        if (StringUtils.isNumeric(projectIdParam)) {
            long projectId = Long.valueOf(projectIdParam);
            return;
        }

        //从body获取项目id
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String body = sb.toString();
        JSONObject json = JSONObject.parseObject(body);
        if (json != null) {
            Long projectId = json.getLong("projectId");
            if (projectId != null) {
                return;
            }
        }

        //从路径获取
        Map map = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if (map != null) {
            Object projectId = map.get("projectId");
            if (projectId != null) {
                return;
            }
        }
    }
}
